import pymysql

class HtmlOutputer(object):
    def __init__(self):
        self.datas = []     # 类里面的全局变量，先存一个数据备份，供output等函数使用

    def collect_data(self, new_url, new_data):
        assert new_url is not None
        assert new_data is not None

        self.datas.append((new_url, new_data))

    def output_html(self):
        """
        输出到output.html
        :return:
        """
        file = open("output.html", mode='w')
        # 从例子可以看出django的模板渲染语言原理。
        file.write("<html>")
        file.write("<body>")

        for row in self.datas:
            file.write("<tr>")
            file.write(f"<td>链接：{row[0]}</td><br>")
            file.write(f"<td>标题：{row[1]['title']}</td><br>")
            file.write(f"<td>简介：{row[1]['summary']}</td><br>")
            file.write(f"<br>")

            file.write("</tr>")
        file.write("</body>")
        file.write("</html>")

    def save_db(self):
        """保存到my_sql数据库"""
        connection = pymysql.connect(
            host="localhost",
            port=3306,
            user="root",
            password="123",
            db="test",
            charset="utf8mb4",   # 可以省略,8.0客户端默认utf-8可以省略，5.x最好带上
            cursorclass=pymysql.cursors.DictCursor    # 返回字典格式的结果集。不写默认返回元组格式

        )

        for row in self.datas:
            href = row[0]
            title = row[1]['title']
            summary = row[1]['summary']

            cursor = connection.cursor()
        # create_table = """CREATE TABLE baike_spider(id INTEGER PRIMARY KEY AUTO_INCREMENT, title VARCHAR(200), summary TEXT, href VARCHAR(200)) """
        # cursor.execute(create_table)
            i_sql = """INSERT INTO baike_spider(title, summary, href) VALUES (%s, %s, %s)"""
            data = (href, title, summary)
            cursor.execute(i_sql, data)
            connection.commit()
